<template>
  <div class="rule-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>评论规则管理</span>
          <el-button type="primary" @click="handleAdd">新增规则</el-button>
        </div>
      </template>

      <!-- 规则列表 -->
      <el-table
        v-loading="loading"
        :data="ruleList"
        style="width: 100%"
      >
        <el-table-column prop="id" label="规则ID" width="80" />
        <el-table-column prop="name" label="规则名称" min-width="150" />
        <el-table-column prop="description" label="规则描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="type" label="规则类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getRuleTypeTag(row.type)">
              {{ getRuleTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 规则表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="ruleRules"
        label-width="100px"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="规则描述" prop="description">
          <el-input
            v-model="ruleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入规则描述"
          />
        </el-form-item>
        <el-form-item label="规则类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择规则类型">
            <el-option label="禁止发布" :value="1" />
            <el-option label="需要审核" :value="2" />
            <el-option label="自动过滤" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="规则参数" prop="params">
          <el-input
            v-model="ruleForm.params"
            type="textarea"
            :rows="3"
            placeholder="请输入规则参数（JSON格式）"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getCommentRules,
  addCommentRule,
  updateCommentRule,
  deleteCommentRule
} from '@/api/admin'

// 状态定义
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增规则')
const ruleList = ref([])
const ruleFormRef = ref(null)

// 表单数据
const ruleForm = ref({
  id: undefined,
  name: '',
  content: '',
  type: null,
  status: 1,
  remark: ''
})

// 表单校验规则
const ruleRules = {
  name: [
    { required: true, message: '请输入规则名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入规则内容', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择规则类型', trigger: 'change' }
  ]
}

// 获取规则列表
const fetchRules = async () => {
  try {
    loading.value = true
    const res = await getCommentRules()
    
    if (res?.code === 200) {
      ruleList.value = res.data
    } else {
      ElMessage.warning(res?.message || '获取规则列表失败')
    }
  } catch (error) {
    console.error('获取规则列表失败:', error)
    ElMessage.error('获取规则列表失败')
  } finally {
    loading.value = false
  }
}

// 新增规则
const handleAdd = () => {
  dialogTitle.value = '新增规则'
  ruleForm.value = {
    id: undefined,
    name: '',
    description: '',
    type: null,
    status: 1,
    remark: ''
  }
  dialogVisible.value = true
}

// 编辑规则
const handleEdit = (row) => {
  dialogTitle.value = '编辑规则'
  ruleForm.value = {
    ...row,
    params: typeof row.params === 'string' ? row.params : JSON.stringify(row.params, null, 2)
  }
  dialogVisible.value = true
}

// 删除规则
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该规则吗？', '警告', {
      type: 'warning'
    })
    
    const res = await deleteCommentRule(row.id)
    if (res?.code === 200) {
      ElMessage.success('删除成功')
      fetchRules()
    } else {
      ElMessage.error(res?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除规则失败:', error)
      ElMessage.error('删除规则失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  if (!ruleFormRef.value) return
  
  try {
    await ruleFormRef.value.validate()
    submitting.value = true
    
    const submitData = {
      ...ruleForm.value,
      params: JSON.parse(ruleForm.value.params)
    }
    
    const api = submitData.id ? updateCommentRule : addCommentRule
    const res = await api(submitData.id, submitData)
    
    if (res?.code === 200) {
      ElMessage.success(submitData.id ? '更新成功' : '添加成功')
      dialogVisible.value = false
      fetchRules()
    } else {
      ElMessage.error(res?.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('提交失败：' + (error.message || '未知错误'))
  } finally {
    submitting.value = false
  }
}

// 获取规则类型文本
const getRuleTypeText = (type) => {
  const texts = {
    1: '禁止发布',
    2: '需要审核',
    3: '自动过滤'
  }
  return texts[type] || type
}

// 获取规则类型标签
const getRuleTypeTag = (type) => {
  const tags = {
    1: 'danger',
    2: 'warning',
    3: 'info'
  }
  return tags[type] || ''
}

// 格式化日期
const formatDate = (dateArray) => {
  if (!dateArray || !Array.isArray(dateArray)) return '暂无'
  const [year, month, day, hour, minute, second] = dateArray
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`
}

// 初始化
onMounted(() => {
  fetchRules()
})
</script>

<style scoped>
.rule-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-radio-group) {
  margin-top: 8px;
}
</style> 